package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.utils.TokenUtil;
import com.neudu.yiyang.pojo.User;
import com.neudu.yiyang.service.MenuService;
import com.neudu.yiyang.service.UserService;
import com.neudu.yiyang.utils.FLAGS;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    JSONReturn jsonReturn;

    @Autowired
    MenuService menuService;


    @Autowired
    UserService userService;

    @Autowired
    TokenUtil tokenUtils;

    @RequestMapping("login")
    public String login(User user, HttpServletRequest request){
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername())
                    .eq(User::getPassword, user.getPassword())
                    .select(User::getId, User::getNickname, User::getUsername, User::getRoleId);
            List<User> users = userService.list(queryWrapper);
            System.out.println(users);

            if (users != null && users.size() > 0){
                User loginuser = users.get(0);
                loginuser.setToken(tokenUtils.getToken());
                return jsonReturn.returnSuccess(loginuser);
            } else {
                    return jsonReturn.returnFailed(FLAGS.LOGIN_FAIL);
            }
        } catch(Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    //获取菜单：当前项目是角色决定菜单，所以查询条件是角色id
    @RequestMapping("getmenus")
    public String getMenusByRoleId(Integer roleid){
        try {
            return jsonReturn.returnSuccess(menuService.getByroleid(roleid));
        } catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}
